package com.meilingcloud.activiti.service.impl;

import com.meilingcloud.activiti.domain.ActWfFormData;
import com.meilingcloud.activiti.domain.dto.HistoryDataDto;
import com.meilingcloud.activiti.service.IActWfFormDataService;
import com.meilingcloud.activiti.service.IFormHistoryDataService;
import com.meilingcloud.common.utils.DateUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RequiredArgsConstructor(onConstructor_ = @Autowired)
@Service
public class FormHistoryDataServiceImpl implements IFormHistoryDataService {

    private final IActWfFormDataService actWfFormdataService;

    @Override
    public List<HistoryDataDto> historyDataShow(String businessKey) {
        List<HistoryDataDto> historyDataDtos = new ArrayList<>();
        List<ActWfFormData> actWfFormDataList = actWfFormdataService.queryByBusinessKey(businessKey);
        Map<String, List<ActWfFormData>> collect = actWfFormDataList.stream().collect(Collectors.groupingBy(ActWfFormData::getTaskNodeName));
        collect.forEach((key, value) -> {
            HistoryDataDto historyDataDto = new HistoryDataDto();
            historyDataDto.setTaskNodeName(value.get(0).getTaskNodeName());
            historyDataDto.setCreateBy(value.get(0).getCreateBy());
            historyDataDto.setCreateTime(DateUtils.parseDateToStr(value.get(0).getCreateTime()));
            historyDataDto.setFormKey(value.get(0).getFormKey());
            historyDataDto.setFormData(value.get(0).getFormData());
            historyDataDto.setFormDesc(value.get(0).getFormDesc());

            historyDataDtos.add(historyDataDto);
        });
        List<HistoryDataDto> historyDataDtoList = historyDataDtos.stream()
                .sorted(Comparator.comparing(HistoryDataDto::getCreateTime))
                .collect(Collectors.toList());
        return historyDataDtoList;
    }
}
